package wangjg.mda.gen;

import java.io.File;
import java.util.Map;

import wangjg.mda.gen.template.FreeMark;
import wangjg.mda.gen.template.TemplateEngine;
import wangjg.mda.gen.template.VelocityImpl;

public class GenUtil {
	
	public static void make(Map<String,Object> rootMap, String templateRoot, File template, File outFile) {
		if(template.equals(outFile)){
			throw new RuntimeException("template file is equal target file.");
		}
		if(!outFile.getParentFile().exists()){
			outFile.getParentFile().mkdirs();
		}
		TemplateEngine te = getTE(outFile.getName().substring(outFile.getName().length()-2));
		te.setTemplateRoot(templateRoot);
		te.process(rootMap, template, outFile);
		if(outFile.length()==0){
			outFile.delete();
		}
	}
	
	public static String evaluate(Map<String,Object> rootMap, String templateRoot, String template){
		String text = template.replaceAll("\\\\\\$", "\\\\\\\\\\$");
		TemplateEngine te = getTE("vm");
		te.setTemplateRoot(templateRoot);
		String out = te.evaluate(rootMap, text);
		return out;
	}

	private static TemplateEngine getTE(String ext){
		TemplateEngine te = null;
		if("fm".equals(ext)){
			te = new FreeMark();
		}else{
			te = new VelocityImpl();
		}
		return te;
	}

}
